<?php defined('BASEPATH') OR exit('No direct script access allowed');
if(session_id() == '') {
    // session isn't started
}

use Facebook\FacebookSession;
use Facebook\FacebookRedirectLoginHelper;
use Facebook\FacebookRequest;
use Facebook\FacebookRequestException;

class Js extends wsFrontend
{
    public function index()
    {
        redirect();
    }

    public function store_screen_size()
    {
        header('Expires: ' . gmdate('D, d M Y H:i:s \G\M\T', time() + 3600));
        $size = array();
        if (!$this->input->is_ajax_request())
            redirect();
        if ($this->input->post('width'))
            $size['width'] = (int)$this->input->post('width');
        if ($this->input->post('height'))
            $size['height'] = (int)$this->input->post('height');
        if ($size['width'] && $size['height']) {
            $this->session->set_userdata('SCREEN_SIZE', $size);
            $this->session->unset_userdata('GLOBAL', false);
        } else {
            $this->session->unset_userdata('SCREEN_SIZE');
        }
        exit;
    }


    public function global_resolution()
    {
        if (!$this->input->is_ajax_request())
            redirect();
        $apply_global = $this->input->post('global');
        $screen_size = $this->session->userdata('SCREEN_SIZE');
        if (!empty($screen_size) && is_array($screen_size)) {
            if (!$apply_global) {
                $this->session->set_flashdata('FLASH_MSG', $this->language->get_text('global-resolution-has-set-successfully', 'js'));
                $this->session->set_userdata('GLOBAL', true);
            } else {
                $this->session->set_flashdata('FLASH_ERROR', $this->language->get_text('GRHRS', 'js'));
                $this->session->unset_userdata('GLOBAL', false);
            }
        } else {
            $this->session->unset_userdata('SCREEN_SIZE');
        }
        exit;
    }

    public function ajax_vote()
    {
        $this->load->library('user_agent');
        if (!$this->input->is_ajax_request() || !$this->user->is_loggedIn() || $this->agent->is_robot())
            redirect();
        $return = array();
        $hash = $this->input->post('hash');
        $types = array(
            'voteup', 'votedown'
        );
        $type = $this->input->post('type');
        if (!in_array($type, $types)) {
            $return['type'] = 'error';
            $return['msg'] = 'Invalid Vote Type';
        } else {
            $this->load->model('wallpaper_model');
            $wallpaper = $this->wallpaper_model->getWallpaperByHASH($hash);
            if (!$wallpaper) {
                $return['type'] = 'error';
                $return['msg'] = $this->language->get_text('wallpaper-hash-doest-exists', 'js');
            } else {
                $alreadyRated = $this->wallpaper_model->is_Wallpaper_ratedBYUser($wallpaper->wallpaper_seq_id, $this->user->get_id());
                if ($alreadyRated) {
                    // Update
                    if ($type == 'voteup') {
                        $update = array(
                            'vote_up' => 1,
                            'vote_down' => 0,
                            'vote_ip' => ip2long($this->input->ip_address())
                        );
                    } else {
                        $update = array(
                            'vote_up' => 0,
                            'vote_down' => 1,
                            'vote_ip' => ip2long($this->input->ip_address())
                        );
                    }
                    $this->db->update('wallpapers_votes', $update, array('vote_seq_id' => $alreadyRated->vote_seq_id));
                } else {
                    //Insert
                    $insert = array(
                        'vote_up' => $type == 'voteup' ? 1 : 0,
                        'vote_down' => $type != 'voteup' ? 1 : 0,
                        'vote_wid' => $wallpaper->wallpaper_seq_id,
                        'vote_uid' => $this->user->get_id(),
                        'vote_date' => date('Y-m-d H:i:s'),
                        'vote_ip' => ip2long($this->input->ip_address())
                    );
                    $this->db->insert('wallpapers_votes', $insert);
                }
                $return['type'] = 'success';
                $return['msg'] = $this->language->get_text('wallpaper-ratted-successfully', 'js');

                $md5 = $this->wallpaper_model->get_wallpaper(array(
                    'category_slug' => $wallpaper->cFullSlug,
                    'wallpaper_slug' => $wallpaper->wallpaper_slug,
                    'wallpaper_hash' => $wallpaper->wallpaper_hash,
                    'md5' => true,
                ));
                delete_md5($md5);
                $return['vote_status'] = $this->wallpaper_model->get_wallpaper_voteStats($wallpaper->wallpaper_seq_id);
            }
        }
        echo json_encode($return);
        exit;
    }

    public function ajax_favourite()
    {
        $this->load->library('user_agent');
        if (!$this->input->is_ajax_request() || !$this->user->is_loggedIn() || $this->agent->is_robot())
            redirect();
        $hash = $this->input->post('hash');
        $this->load->model('wallpaper_model');
        $wallpaper = $this->wallpaper_model->getWallpaperByHASH($hash);
        $return = array();
        if (!$wallpaper) {
            $return['type'] = 'error';
            $return['msg'] = $this->language->get_text('wallpaper-hash-doest-exists', 'js');
        } else {
            $is_userAddedToFavourite = $this->wallpaper_model->is_userAddedToFavourite($wallpaper->wallpaper_seq_id, $this->user->get_id());
            if (!$is_userAddedToFavourite) {
                $insert = array(
                    'wf_date' => date('Y-m-d H:i:s'),
                    'wf_ip' => ip2long($this->input->ip_address()),
                    'wf_uid' => $this->user->get_id(),
                    'wf_wid' => $wallpaper->wallpaper_seq_id
                );
                $this->db->insert('wallpapers_favourites', $insert);

                $return['status'] = 1;
                $return['msg'] = $wallpaper->wallpaper_name . ' - ' . $this->language->get_text('wallpaper-has-added-to-your-favourite', 'js');
            } else {
                $this->db->delete('wallpapers_favourites', array('wf_seq_id' => $is_userAddedToFavourite->wf_seq_id));
                $return['status'] = 0;
                $return['msg'] = $wallpaper->wallpaper_name . ' - ' . $this->language->get_text('WHRFYYF', 'js');
            }
            $md5 = $this->wallpaper_model->get_wallpaper(array(
                'category_slug' => $wallpaper->cFullSlug,
                'wallpaper_slug' => $wallpaper->wallpaper_slug,
                'wallpaper_hash' => $wallpaper->wallpaper_hash,
                'md5' => true,
            ));
            delete_md5($md5);
            $return['type'] = 'success';
        }
        echo json_encode($return);
        exit;
    }

    public function load_more_comment($wallpaper_hash)
    {
        if ($wallpaper_hash && $this->input->is_ajax_request() && $offset = $this->input->post('offset')) {
            $this->load->model('wallpaper_model');
            $comment_db = array(
                'wallpaper_hash' => $wallpaper_hash,
                'per_page' => $this->config->item('comment_limit'),
                'offset' => $offset,
            );
            if (!$this->config->item('facebook_comment')) {
                $this->load->helper('date');
            }
            $data['comments'] = $this->wallpaper_model->get_comments($comment_db);
            $return['html'] = $this->tpl->fetch('contents/comments_list', $data);
            $return['offset'] = $comment_db['offset'] + count($data['comments']);
            echo json_encode($return);
            exit;
        }
    }

    public function report_comment()
    {
        if (!$this->input->is_ajax_request())
            redirect();
        $return = array();
        if (!$this->user->is_loggedIn())
            $return['login_required'] = true;
        else {
            $this->load->library('form_validation');
            $this->form_validation->set_rules('your_msg', $this->language->get_text('your-msg', 'js'), 'required|min_length[10]');
            $this->form_validation->set_rules('comment_id', $this->language->get_text('comment-id', 'js'), 'required');
            if ($this->form_validation->run()) {
                $insert_data = array(
                    'comment_seq_id' => (int)$this->input->post('comment_id'),
                    'report_msg' => strip_tags($this->input->post('your_msg')),
                    'user_seq_id' => (int)$this->user->get_id(),
                    'report_date' => date('Y-m-d H:i:s'),
                    'report_status' => 0,
                );
                $this->db->insert('comments_reports', $insert_data);
                $return['id'] = $insert_data['comment_seq_id'];
                $return['success'] = $this->language->get_text('YHSRTCI', 'js') . ' - ' . $insert_data['comment_seq_id'];
            } else {
                $return['error'] = validation_errors();
            }
        }
        echo json_encode($return);
        exit;
    }

    public function itemWidth()
    {
        if (!$this->input->is_ajax_request())
            redirect();
        $width = $this->input->post('width');
        $per_row = $this->input->post('per_row');
        if ($width && $per_row) {
            $this->session->set_userdata('item_width', $width);
            $this->session->set_userdata('per_row', $per_row);
        }
        exit;
    }

    public function upload_cover()
    {
        if (!$this->input->is_ajax_request())
            redirect();
        $allowed_type = array('facebook', 'google');
        $type = $this->input->post('type');
        if (!in_array($type, $allowed_type))
            exit;
        $x = $this->input->post('x');
        $y = $this->input->post('y');
        $w = ceil($this->input->post('w'));
        $h = ceil($this->input->post('h'));

        $wall_hash = $this->input->post('w_hash');
        $return = array();
        $return['redirect_msg'] = $this->language->get_text('redirecting-to-login-page', 'js');
        $return['approve_url_msg'] = $this->language->get_text('redirecting-to-approve-image', 'js');
        $this->load->model('wallpaper_model');
        $wallpaper = $this->wallpaper_model->get_wallpaper(array('wallpaper_hash' => $wall_hash));
        if (!$wallpaper)
            $return['error'] = $this->language->get_text('wallpaper-not-found', 'js');
        else {
            $search_replace = array(
                '{C_SLUG_FULL}' => $wallpaper->cFullSlug,
                '{C_SLUG}' => $wallpaper->category_slug,
                '{W_SLUG}' => $wallpaper->wallpaper_slug,
                '{W_HASH}' => $wallpaper->wallpaper_hash,
            );
            switch ($type) {
                case'facebook':
                    $url = $this->route_links->build_link('wallpapers_page_cover_facebook', $search_replace);
                    if (version_compare(PHP_VERSION, '5.4.0', '<')) {
                        $this->session->set_flashdata('ERROR', 'The Facebook SDK v4 requires PHP version 5.4 or higher.');
                        $return['redirect'] = current_url();
                    }

                    $fb_token = $this->session->userdata('fb_token');

                    $session = FALSE;
                    if ($fb_token) {
                        $session = new FacebookSession($fb_token);
                        try {
                            if (!$session->validate()) {
                                $session = FALSE;
                            }
                        } catch (Exception $e) {
                            //  $session = FALSE;
                        }
                    }

                    FacebookSession::setDefaultApplication($this->config->item('facebook_appId'), $this->config->item('facebook_secret'));

                    if (!$session) {
                        $helper = new FacebookRedirectLoginHelper($this->route_links->build_link('account_facebook') . '?redirect=' . $url);
                        try {
                            $session = $helper->getSessionFromRedirect();
                        } catch (FacebookRequestException $ex) {
                            // When Facebook returns an error
                        } catch (Exception $ex) {
                            // When validation fails or other local issues
                        }
                    }

                    /* if ($session) {
                        $user_profile = (new FacebookRequest(
                            $session, 'GET', '/me'
                        ))->execute()->getGraphObject();
                    } else {
                        $return['redirect'] = $helper->getLoginUrl(facebook_permissions());
                    } */


                    if (isset($user_profile)) {
                        $source = $this->crop_cover_image($wallpaper->wallpaper_image_path, $x, $y, $w, $h);
                        $fb = new FacebookRequest(
                            $session, 'POST', '/me/photos', array(
                                'source' => new CURLFile($source, 'image/jpeg'),
                            )
                        );
                        $respond = $fb->execute();
                        $photo_uploaded = $respond->getGraphObject();

                        $return['success'] = $wallpaper->wallpaper_name . ' ' . $this->language->get_text('CHSUTYP', 'js');
                        $return['approve_url'] = 'https://facebook.com/' . $user_profile->getProperty('id') . '?preview_cover=' . $photo_uploaded->getProperty('id');
                    }
                    break;
                case 'google':

                    break;
            }
        }
        echo json_encode($return);
        exit;
    }

    private function crop_cover_image($image_path, $x, $y, $width, $height)
    {
        $this->image_workshop->base_path_return = true;

        $image = $this->image_workshop->crop_image(ORIGINALS_FOLDER_WF . '/' . $image_path, IMAGE_WIDTH_THUMB, 0, false, 'thumbnail');

        $img_r = imagecreatefromjpeg($image);
        $dst_r = ImageCreateTrueColor($width, $height);
        imagecopyresampled($dst_r, $img_r, 0, 0, $x, $y, $width, $height, $width, $height);

        $pathInfo = pathinfo($image);
        $cache_name = $pathInfo['filename'] . '-' . $width . 'x' . $height . '-' . $x . '-' . $y . '.' . $pathInfo['extension'];
        $cache_folder = MAIN_CACHE_PATH . '/' . abs(crc32(trim('cover', DS) . DS . $pathInfo['dirname']));
        $full_cache_path = $cache_folder . '/' . $cache_name;
        if (!is_dir($cache_folder))
            mkdir($cache_folder, 0777, true);
        imagejpeg($dst_r, $full_cache_path, 100);
        imagedestroy($dst_r);
        return FCPATH . $full_cache_path;
    }
}
